
/*
This is for cash slate

*/

    var lastcheck = 0;
    var current_check = 0;  //this is what we use to keep current check time
    var syncing = 0;  //controls if syncing is on or off
  
$(document).ready(function()
{
//BUTTONS

 $('#check_total').click(function(){
        var d = fetchall(db.execute('select * from users_info'));
        confirm($.toJSON(d))
        var d = fetchall(db.execute('select * from menu_info'));
        confirm($.toJSON(d))
    });


//USER INTERACTIONS
 $('#logout').click(function(){
        //db.execute('UPDATE login_info SET logout_ms= ? WHERE logout_ms IS NULL ORDER BY login_ms LIMIT 1',[new Date().getTime()])
        db.execute('UPDATE login_info SET logout_ms= ? WHERE logout_ms IS NULL',[new Date().getTime()])
        $('#idcode_head').html('icode');
        $('#user_head').html('user');
        station_login_dlg();
        

        
    });  
 $('#syncme').click(function(){
        local_sync(function(){draw_checks();draw_menu();draw_current_check();});
    });
    
 $('#open_check').click(function(){
        open_check();
    });    
 $('#check_kill').click(function(){
        check_kill(current_check);
    });      
  $('#check_guests').click(function(){
        check_guests(current_check,$('#check_guest_txt').val())
    });    
 $('#station_close').click(function(){
        //db.execute('UPDATE login_info SET logout_ms= ? WHERE logout_ms IS NULL ORDER BY login_ms LIMIT 1',[new Date().getTime()])
        //db.execute('DROP TABLE branch_info');
        syncing = 0;
        db.execute('UPDATE branch_info SET station_open= ?',[0])
        get_branch();
    });    
    
//DIALOGS

    var station_login_dlg = function(){
        syncing = 0;
        var dtext = $('<div  title="Logging in a Station"><h2>Please enter your PIN</h2></div>');
        $('<label>Login</label><br/><input type="text" id="pin" size="20" ></input><br/>').appendTo(dtext);
        dtext.dialog({
            height: 300,width:350,modal: false,overlay: {backgroundColor: '#000',opacity: 0.5},
            buttons: {
                'Login': function() {
                    //This was how we logged on from the server
                    /*var brbs = get_branch(true);
                                doajax('station_login',{'brname':brbs[0],'bsname':brbs[1],'pin':$('#pin').val()},function(data){
                                    $(dtext).dialog('destroy').remove();
                                    station_login(data.e_name,data.e_idcode)
                                });
                                */
                  //this is how we log on without the internet
                    var d = fetchall(db.execute("SELECT * FROM users_info WHERE e_pin=?",[$('#pin').val()]));
                    if(d.length == 2){
                        $(dtext).dialog('destroy').remove();
                        station_login(d[1][0],d[1][1])
                        
                    }
                    else{confirm('sorry, cant find that user pin')}
                
                }
            },
            close:function(){station_login_dlg();}
        });
    
    }
        
    
    var station_login = function(name,idcode){
        db.execute('INSERT INTO login_info (e_name,e_idcode,login_ms,logout_ms) VALUES (? , ?, ?,?)',[name,idcode,new Date().getTime(), null ])
        $('#idcode_head').html(idcode);
        $('#user_head').html(name);
        syncing=1;
    }    
    
//FILL HEADER
    

    var get_branch = function(impotent){
        var d = fetchall(db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='branch_info'"));
        if(d.length==2){
            var d = fetchall(db.execute('select * from branch_info'));
            if(d.length==2 && d[1][2]==1){
                $('#bs_head').html(d[1][1]);
                $('#br_head').html(d[1][0]);
                var usr = fetchall(db.execute("SELECT * FROM login_info WHERE logout_ms IS NULL"));
                if(usr.length > 1){
                    $('#idcode_head').html(usr[1][1]);
                    $('#user_head').html(usr[1][0]);
                }
                else{if(!impotent){station_login_dlg();}}
                return [d[1][0],d[1][1],d[1][3],d[1][4]]
            }
            else{
                confirm('I am sorry, you are not logged in, type 2, try loggin in again')
                window.location='/';
            }
        }
        else{
            confirm('I am sorry, you are not logged in, try loggin in again')
            window.location='/';
        }
    }
    
//CHECKS AND STUFF
    var open_check = function(){
        var dt = new Date().getTime();
        db.execute('INSERT INTO checks_info (created_at,created_by,killed_at,killed_by,rev,local_edit,sale_total) VALUES (?,?,?,?,?,?,?)',
                    [dt,$('#idcode_head').html(),0,'',0,'',0])
        current_check = dt;
        draw_checks();
    }
    
    var check_kill = function(checkid){
        var dt = new Date().getTime();
        var name = $('#idcode_head').html()
        var d = fetchall(db.execute("SELECT killed_at,killed_by,local_edit FROM checks_info WHERE created_at=?",[checkid]));
        var locale = d[1][2]
        //confirm($.toJSON(d[1]))
        locale += '|killed_at:'+d[1][0]+':'+dt+':'+name
        locale += '|killed_by:'+d[1][1]+':'+name+':'+name
        db.execute('UPDATE checks_info SET killed_at=?,killed_by=?,local_edit=? WHERE created_at =?',
                            [dt,name,locale,checkid])
        
        draw_checks();
    }
        
    var check_guests = function(checkid,new_value){
        var dt = new Date().getTime();
        var name = $('#idcode_head').html()
        var d = fetchall(db.execute("SELECT number_guests,local_edit FROM checks_info WHERE created_at=?",[checkid]));
        var locale = d[1][1]
        locale += '|number_guests:'+d[1][0]+':'+new_value+':'+name
        db.execute('UPDATE checks_info SET number_guests=?,local_edit=? WHERE created_at =?',
                            [new_value,locale,checkid])
        
        draw_checks();
    }
    
    
    var get_item = function(key){
        var d = fetchall(db.execute("SELECT * FROM menu_info WHERE dkey=?",[key]));
        if(d.length == 2){
            return d[1]
        }
        else{return []}
    
    }
    
    var draw_checks = function(){
        var d = fetchall(db.execute("SELECT * FROM checks_info ORDER BY created_at"));

        $('#dis_checks').html('');  
        for(var i=0;i<d.length;i++){
            if(d[i][0]==current_check){$('<div id="'+d[i][0]+'">--<b>'+d[i]+'</b></div>').appendTo($('#dis_checks'));}
            else{$('<div id="'+d[i][0]+'">--'+d[i]+'</div>').appendTo($('#dis_checks'));}
            
        }
        $("#dis_checks > *").click(function(){
                current_check = $(this).attr('id')
                draw_current_check();draw_checks();
            });
        
         
    }
    
    var draw_current_check = function(){
        var d = fetchall(db.execute("SELECT * FROM items_info WHERE checkid=? ORDER BY name",[current_check]));
        $('#dis_check').html('');  
        for(var i=0;i<d.length;i++){
           $('<div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+d[i]+'</div>').appendTo($('#dis_check')); 
        } 
    }
    
    var draw_menu = function(){
        var d = fetchall(db.execute("SELECT * FROM menu_info ORDER BY name"));

        $('#dis_menu').html('');  
        for(var i=0;i<d.length;i++){
            $('<div id="'+d[i][0]+'">--'+d[i]+'</div>').appendTo($('#dis_menu')); 
        } 
        
        $("#dis_menu > *").click(function(){
                var item = get_item($(this).attr('id'));
                db.execute('INSERT INTO items_info (ordered_at,ordered_by,name,price,quantity,checkid,rev,local_edit) VALUES (?,?,?,?,?,?,?,?)',
                        [new Date().getTime(),$('#idcode_head').html(),item[1],item[3],1,current_check,0,''])
                draw_checks();draw_current_check();
            });
    
    }
    
    
    
    var local_state = function(){
        ls = {'current':{},'edit': {'checks':[],'itemso':[]},'new': {'checks':[],'itemso':[]}};
        

        var d = fetchdict(db.execute("SELECT * FROM checks_info ORDER BY created_at"));
        for(var i=0;i<d.length;i++){
            var itemso = {};
            var d2 = fetchdict(db.execute("SELECT * FROM items_info WHERE checkid=? ORDER BY ordered_at",[d[i]['created_at']]));
            for(var j=0;j<d2.length;j++){
                itemso[d2[j]['ordered_at']] = d2[j]['rev'];
                if(d2[j]['rev'] ==0){ls['new']['itemso'].push(d2[j]);}
                if(d2[j]['local_edit'] !=''){ls['edit']['itemso'].push([d[i]['created_at'],d2[j]['ordered_at'],d2[j]['local_edit']]);}
            }
            ls['current'][d[i]['created_at']] = [d[i]['rev'],itemso];
           

            if(d[i]['rev'] ==0){ls['new']['checks'].push(d[i]);}
            if(d[i]['local_edit'] !=''){ls['edit']['checks'].push([d[i]['created_at'],d[i]['local_edit']]);}
        }
        return ls
    
    }
    
    var clean_db = function(){
    //should make sure we dont have any items that dont have a check
    }
    
    
    local_sync = function(func){
    //This needs to sync user info, menu info, open orders
        var brbs = get_branch();
        /*need to decide on a data structure 
                so if anything in a chech changes, the check rev changes
                usually, we just send up the id stuff, and revs, and get information sent back down.  
                if we have changes, we push up a list of changes, it comes back if it was succesfull or not.  We will do this later
                local_state = {'current':{checkID:[rev,{itemoID:rev}]}, 'edit':{'checks':[id,'property:newvalue|property:newvalue']  ,'itemso':[checkid,id,'property:newvalue|property:newvalue']},'new':{'checks':[whole dict from check]  ,'itemso':[whole dict from items]}}
                
                and we get returned to us
                checks_upt = {'remove':[list of IDs to remove],'new':[full data that we can just plug in],  'update':[[checkID,[[variable,newvalue],[variable2,value]] ],........] }
                itemso_upt = same as above
            */
        doajax('local_sync',{'bsname':brbs[1],'brname':brbs[0],'user_rev':brbs[2],'menu_rev':brbs[3],'local_state':local_state()},function(data){
                //if(data.errors.length != 0){confirm('ERRORS: '+$.toJSON(data.errors))}
                //confirm($.toJSON(data.checks_upt['errors']))
                //updated all checks that have changed
                
                //finds all the erros, tells us about them, then gets rid of them so they dont happen again
                if(data.checks_upt['errors'] !=[]){
                    for(var i=0;i<data.checks_upt['errors'].length;i++){
                        var check_errors = data.checks_upt['errors'][i];
                        var d = fetchall(db.execute("SELECT local_edit FROM checks_info WHERE created_at=?",[check_errors[0]]));
                        var locale = d[1][0].split('|');
                        //confirm(locale)
                        //confirm(check_errors)
                        for(var j=0;j<check_errors[1].length;j++){
                            confirm('ERROR: '+check_errors[1][j])
                            for(var k=0;k<locale.length;k++){
                                if(locale[k].search(check_errors[1][j])!=-1){locale.remove(k)}
                            }
                        }
                        
                        var dbstr = 'UPDATE checks_info SET local_edit= ? WHERE created_at =?'
                        db.execute(dbstr,[locale.join('|'),check_errors[0]])
                    }
                }
                
                if(data.checks_upt['update'] !=[]){
                    for(var i=0;i<data.checks_upt['update'].length;i++){
                        var check_update = data.checks_upt['update'][i];
                        var d = fetchall(db.execute("SELECT local_edit FROM checks_info WHERE created_at=?",[check_update[0]]));
                        var locale = d[1][0].split('|');
                        //confirm(locale)
                        for(var j=0;j<check_update[1].length;j++){
                            var dbstr = 'UPDATE checks_info SET '+check_update[1][j][0]+'= ? WHERE created_at =?'
                            //confirm($.toJSON([dbstr,[check_update[1][j][2],check_update[0]]]))
                            db.execute(dbstr,[check_update[1][j][2],check_update[0]])
                            for(var k=0;k<locale.length;k++){
                                if(locale[k].search(check_update[1][j][0])!=-1){locale.remove(k)}
                            }
                        }
                        //confirm(locale)
                        var dbstr = 'UPDATE checks_info SET local_edit= ? WHERE created_at =?'
                        db.execute(dbstr,[locale.join('|'),check_update[0]])
                    }
                }
                
                //updating all itemo that have changed
                if(data.itemso_upt['update'] !=[]){
                    for(var i=0;i<data.itemso_upt['update'].length;i++){
                        var io_update = data.itemso_upt['update'][i];
                        for(var j=0;j<io_update[1].length;j++){
                            var dbstr = 'UPDATE items_info SET '+io_update[1][j][0]+'= ? WHERE ordered_at =?'
                            db.execute(dbstr,[io_update[1][j][2],io_update[0]])
                        }
                    }   
                }
                
                //adding all the checks that we downloaded
                if(data.checks_upt['new'] !=[]){
                    for(var i=0;i<data.checks_upt['new'].length;i++){
                        db.execute('INSERT INTO checks_info (created_at,created_by,killed_at,killed_by,rev,local_edit,sale_total,number_guests) VALUES (?,?,?,?,?,?,?,?)',
                                    data.checks_upt['new'][i])
                    }
                }
                
                //adding all itemo that are new
                if(data.itemso_upt['new'] !=[]){
                    for(var i=0;i<data.itemso_upt['new'].length;i++){
                        db.execute('INSERT INTO items_info (ordered_at,ordered_by,name,price,quantity,checkid,rev,local_edit) VALUES (?,?,?,?,?,?,?,?)',
                                    data.itemso_upt['new'][i])
                    }
                }
                
                //removing checks and items that are closed
                var dt = new Date().getTime();
                var killed = fetchall(db.execute("SELECT created_at FROM checks_info WHERE killed_at < ? AND killed_at != ?",[dt-10000,0]));
                for(var i=1;i<killed.length;i++){
                        var cid = parseInt(killed[i])
                        db.execute('DELETE FROM items_info WHERE checkid = ?',[cid]);
                        db.execute('DELETE FROM checks_info WHERE created_at = ?',[cid]);
                }
                
                
                
                //confirm($.toJSON(data.itemso_upt))
                
                
                if(data.users !=[]){
                    db.execute('DELETE FROM  users_info');
                    for(var i=0;i<data.users.length;i++){
                        db.execute('INSERT INTO users_info (e_name,e_idcode,e_pin) VALUES (?,?,?)',data.users[i])
                    }
                }
                if(data.menu !=[]){
                    db.execute('DELETE FROM  menu_info');
                    for(var i=0;i<data.menu.length;i++){
                        db.execute('INSERT INTO menu_info (dkey,name,description,price) VALUES (?,?,?,?)',data.menu[i])
                    }
                }
                
                
                
                if(func){func()}
            })                            

  //                          db.execute('insert into branch_info VALUES (?,?,?,?,?)',[data.br_name,data.bs_name,1,0,0])
    //                         users_info (e_name TEXT,e_idcode TEXT, e_pin TEXT)');
      //                       menu_info (dkey TEXT, name TEXT,description TEXT, price REAL)');
        //                     checks_info (created_at INTEGER,created_by TEXT, killed_at INTEGER,killed_by TEXT, rev,local_edit,sale_total)');
          //                   items_info (ordered_at INTEGER,ordered_by TEXT,name TEXT,price REAL, quantity INTEGER, checkid INTEGER,rev,local_edit)');
    }

    draw_checks();draw_menu();
    //local_sync(function(){draw_checks();draw_menu();draw_current_check();});
    
    
    var t;
    timedCount = function(){
        if(syncing==1){
            local_sync(function(){draw_checks();draw_menu();draw_current_check();});
        }
        //confirm('ping')
        time += 5;
        t=setTimeout("timedCount()",5000);
    }
    
    
    timedCount();
    //d=local_state();
    //confirm($.toJSON(d))
})
                               
